package dlb.busstop.json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Build;

public abstract class JSONParser {

	protected static final String TAG = "JSONParser";
	
	public static JSONParser getInstance() {
		/*
		 * according to this ->
		 * http://android-developers.blogspot.com/2011/09/androids
		 * -http-clients.html guide we need to choose implementation depending
		 * on android version
		 */
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
			return new PostGingerbreadJSONParser();
		} else {
			return new PreGingerbreadJSONParser();
		}
	}

	/**
	 * Parses resource at specified url and returns {@link JSONObject}
	 * 
	 * @param url
	 *            - url of the resource
	 **/
	public JSONObject parse(String url) throws JSONException, IOException {
		try {
			InputStream in = getInputStream(url);
			return new JSONObject(readToEnd(in));
		} finally {
			release();
		}
	}

	private String readToEnd(InputStream in) throws IOException {
		if (in == null) {
			throw new RuntimeException("Unable to read null InputStream");
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buff = new byte[1024];
		int read;
		while ((read = in.read(buff)) != -1) {
			bos.write(buff, 0, read);
		}
		return new String(bos.toByteArray());
	}

	protected abstract InputStream getInputStream(String url)
			throws IOException;
	
	protected abstract void release();

}
